//
//  ViewModelType.swift
//  SwiftHub
//
//  Created by Khoren Markosyan on 6/30/18.
//  Copyright © 2018 Khoren Markosyan. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import ObjectMapper
import NSObject_Rx

protocol ViewModelType {
    associatedtype Input
    associatedtype Output

    func transform(input: Input) -> Output
}

class ViewModel: NSObject {
    
//    let disposeBag = DisposeBag()
    let loading = ActivityIndicator()
    let provider: SwiftSignAPI
    let parsedError = PublishSubject<ApiError>()
    let error = ErrorTracker()
 
    var initInfo: UserInitInfo?
    
    convenience init(provider: SwiftSignAPI,_ initInfo: UserInitInfo) {
        self.init(provider: provider)
        self.initInfo = initInfo
    }
    
    init(provider: SwiftSignAPI) {
        self.provider = provider
        super.init()
      
        error.asObservable().map { (error) -> ApiError? in
            do {
                let errorResponse = error as? MoyaError
                if let body = try errorResponse?.response?.mapJSON() as? [String: Any],
                   let errorResponse = Mapper<ErrorResponse>().map(JSON: body) {
                    LogInfo(errorResponse)
                    return ApiError.serverError(response: errorResponse)
                }
            } catch {
                LogError(error)
            }
            return nil
        }.filterNil().bind(to: parsedError).disposed(by: rx.disposeBag)

        error.asDriver().drive(onNext: { (error) in
            LogError(error)
        }).disposed(by: rx.disposeBag)
    }


}
